package com.syxbyi._3tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ChatClientListener implements Runnable {

    private User user;
    private Socket socket;

    ChatClientListener(User user, Socket socket) {
        this.user = user;
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while(true) {
                // 由于接收端和发送端共用一个socket，所以如果发送端首先关闭了socket，这里会发生socket异常，不知道怎么解决
                String msg = bufferedReader.readLine();
                // 因为边监听边接收输入，所以命令行是这样的 User> _
                // 所以如果直接打印就会打印在接收输入那里了……只会这样整了
                System.out.println();
                System.out.println(msg);
                System.out.printf("%s> ", user.getName());
            }
        } catch (IOException e) {
//            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
